import { Injectable, UnauthorizedException } from '@nestjs/common'
import { PrismaService } from 'src/prisma/prisma.service'
import { CreateAuthDto } from './dto/create-auth.dto'
import { JwtService } from '@nestjs/jwt'
import * as argon2 from 'argon2'

@Injectable()
export class AuthService {
  constructor(
    private prismaService: PrismaService,
    private jwtService: JwtService,
  ) {}

  async signin(name: string, password: string) {
    const [user] = await this.prismaService.user.findMany({
      where: {
        name,
      },
    })

    if (!user) {
      throw new UnauthorizedException('用户名不存在')
    }
    const isPasswordValid = await argon2.verify(user.password, password)
    if (!isPasswordValid) {
      throw new UnauthorizedException('密码错误')
    }
    const payload = { sub: user.id, username: user.name }
    return {
      access_token: await this.jwtService.signAsync(payload),
    }
  }

  async signup(createUserDto: CreateAuthDto) {
    const user = await this.prismaService.user.findUnique({
      where: {
        name: createUserDto.name,
      },
    })
    if (user) {
      throw new UnauthorizedException('用户名已存在')
    }
    const { password } = createUserDto
    const hashedPassword = await argon2.hash(password)

    return await this.prismaService.user.create({
      data: {
        name: createUserDto.name,
        password: hashedPassword,
        email: createUserDto.email,
      },
    })
  }
}
